package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * author by itheima
 *
 * @Date 2022/2/12
 * Description
 */
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    //   exchange 封装了request response
    //chain 过滤器链
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.获取authorization参数
        String authorization = request.getQueryParams().getFirst("authorization");
        //3.判断参数是否为admin
        if ("admin".equals(authorization)) {
            //4.如果是 就放行
            return chain.filter(exchange);
        }

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //5.如果不是 就拦截终止请求
        return response.setComplete();
    }
}
